package com.baigao.springboot.controller;
 
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
 

import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;
 
@Controller
public class UploadController {
    @Value("${file.path}")
    private String filePath;
 
    @RequestMapping("/upload")
    @ResponseBody
    public String upload(MultipartFile file) throws  Exception{
        //a.jpg
        String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
 
        String fileName = UUID.randomUUID().toString() + extName;
 
        File file2 = new File(filePath + fileName);
        if(!file2.exists()){
            //先得到文件的上级目录，并创建上级目录，在创建文件
            file2.getParentFile().mkdir();
            
            // 或  file2.mkdir();
        }
        FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(new File(filePath + fileName)));
        return fileName;
    }
}
